﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace MefBasic.Helper
{
    public class SynchronizationContextHelper
    {
        private static readonly object LockObject=new object();
        private static SynchronizationContextHelper _instance;
        private SynchronizationContext _context;

        public static SynchronizationContextHelper Instance
        {
            get
            {
                if(_instance==null)
                {
                    lock (LockObject)
                    {
                        if(_instance==null)
                        {
                            _instance=new SynchronizationContextHelper();
                        }
                    }
                }
                return _instance;
            }
        }

        public void SendInBackground(Action<object> action, object state)
        {
            if (Application.Current==null)
                return;
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,new ParameterizedThreadStart(action), state);
        }
        public void Send(Action<object> action, object state)
        {
            _context.Send(d=>action(d), state);
        }
        public void SetContext(SynchronizationContext context)
        {
            _context = context;
        }
    }
}
